package com.laikan.reader.bookstore.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.RankingCategoryAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.RankingCategoryBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * 排行分类页 男榜 女榜
 * Created by gwt on 2016/10/20.
 */
public class RankCategoryActivity extends BasicActivity {

    private RelativeLayout rl_back_layout;
    private ImageView iv_back;
    private TextView tv_title;
    private ListView listview;
    private LinearLayout ll_search_img;
    private RelativeLayout common_loaddata_notice;
    private TextView common_prompt_content;
    private TextView common_refresh_net;
    private CircleProgressBar circleProgressBar;
    private Drawable drawable_back_tv;
    private RankingCategoryAdapter rankCateAdapter;
    private TouchSwipeRefreshLayout pull_to_refresh_pro;
    private ProgressBar_Modern bottom_load_progressbar;
    private long mLoadDelaynternalTime;
    private String rankUrl;
    private int pageNo;
    private int pageSize;
    private HashSet mRankIdList = new HashSet();
    private boolean isPullDown = true;// 是否下拉
    private int mCurrentPage = 1; //当前页
    private int END_LIST_PAGE = -1; //最后页
    private int PAGE_LIMIT_SIZE = 10; //每页10条
    private ArrayList<RankingCategoryBean.DataBean> rankDataList;
    private boolean isShowBottomProgressBar = true; //是否显示底部加载进度条
    private View foot_view;
    private String title;
    private boolean isShowOrder;
    private ImageView common_prompt_image;
    private int mPullUpPage = 2;

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_ranking_category);
        foot_view = View.inflate(mContext, R.layout.item_comment_foot_view,null);
        rl_back_layout = (RelativeLayout)findViewById(R.id.rll_back_layout);
        pull_to_refresh_pro = (TouchSwipeRefreshLayout)findViewById(R.id.pull_to_refresh_pro); //下拉刷新圆形
        pull_to_refresh_pro.setColorSchemeResources(R.color.C_66ccdd);
        iv_back = (ImageView)findViewById(R.id.iv_title_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        listview = (ListView)findViewById(R.id.listView);
        listview.addFooterView(foot_view);
        foot_view.setVisibility(View.GONE);
        foot_view.setOnClickListener(null);
        ll_search_img = (LinearLayout)findViewById(R.id.ll_search_img);
        bottom_load_progressbar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        //无网络连接
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net); //点击重新加载
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading); //圆形
        common_prompt_image = (ImageView)findViewById(R.id.common_prompt_image);
        pull_to_refresh_pro.setChildView(listview);
    }

    @Override
    protected void initData() {
        rankDataList = new ArrayList<>();
        rankCateAdapter = new RankingCategoryAdapter(mContext, rankDataList);
        Intent intent = getIntent();
        String action = intent.getAction();
        if("from_more_data".equals(action)){
            //查看更多
            title = intent.getStringExtra("title");
            rankUrl = intent.getStringExtra("rankUrl");
            isShowOrder = intent.getBooleanExtra("isShowOrder",false);//是否显示排序序号
            if(!isShowOrder){
                rankCateAdapter.setNumberGone();
            }
        }else{
            //排行首页
            title = intent.getStringExtra("title");
            rankUrl = intent.getStringExtra("rankUrl");  //排行url
            pageNo = intent.getIntExtra("pageNo", 1);
            pageSize = intent.getIntExtra("pageSize", 10);
        }
        tv_title.setText(title);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);

        listview.setAdapter(rankCateAdapter);

        if (ActivityUitl.isNetworkAvailable(mContext)) {
            getDataFromNet(true);
        }else {
            common_loaddata_notice.setVisibility(View.VISIBLE);
            circleProgressBar.setVisibility(View.INVISIBLE);
            common_prompt_content.setText(R.string.laikan_network_anomaly);
        }
    }

    private ArrayList<RankingCategoryBean.DataBean> updateListData(ArrayList<RankingCategoryBean.DataBean> list) {
        ArrayList<RankingCategoryBean.DataBean> refreshList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!mRankIdList.contains(list.get(i).getId())) {
                mRankIdList.add(list.get(i).getId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(rankDataList);
        rankDataList.clear();
        rankDataList.addAll(refreshList);
        refreshList.clear();
        return rankDataList;
    }

    private ArrayList<RankingCategoryBean.DataBean> loadMoreData(ArrayList<RankingCategoryBean.DataBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (!mRankIdList.contains(list.get(i).getId())) {
                mRankIdList.add(list.get(i).getId());
                rankDataList.add(list.get(i));
            }
        }
        return rankDataList;
    }

    //访问网络
    private BaseDataBean<RankingCategoryBean> result;

    private void getDataFromNet(boolean isLoad) {
        if (isLoad) {
//            showDialog();
            common_loaddata_notice.setVisibility(View.VISIBLE);
            circleProgressBar.setVisibility(View.VISIBLE);
            common_prompt_content.setVisibility(View.GONE);
            common_prompt_image.setVisibility(View.GONE);
            common_refresh_net.setVisibility(View.GONE);
        }
        HashMap<String, String> map = new HashMap<>();
        if(isPullDown){
            map.put("pageNo", mCurrentPage+"");
        }else{
            map.put("pageNo", mPullUpPage+"");
        }
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                pull_to_refresh_pro.setRefreshing(false);
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<RankingCategoryBean>>() {
                    }.getType();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            KLog.e(result.getError_msg());
                            showErrorView(1);
                        }else {
                            if (0 == result.getData().getBookList().size()) { //最后一页没有数据了
                                foot_view.setVisibility(View.VISIBLE);
                                isShowBottomProgressBar = false;
                            }else {
                                foot_view.setVisibility(View.GONE);
                                isShowBottomProgressBar = true;
                                closeErrorView();

                                if (isPullDown) {
                                    // 下拉刷新
                                    rankCateAdapter.setDatas(updateListData((ArrayList<RankingCategoryBean.DataBean>)result.getData().getBookList()));
                                }else {
                                    // 上拉加载,数据追加
                                    rankCateAdapter.setDatas(loadMoreData((ArrayList<RankingCategoryBean.DataBean>)result.getData().getBookList()));
                                    mPullUpPage ++;
                                }
                                //不足10条时说明没有下一页了
                                if(result.getData().getBookList().size() < 10){
                                    foot_view.setVisibility(View.VISIBLE);
                                    isShowBottomProgressBar = false;
                                }
//                                mCurrentPage = rankDataList.size() / PAGE_LIMIT_SIZE + 1+"";
                                mCurrentPage ++; //增加页数
                            }
                        }
                    }else {
                        showErrorView(1);
                    }
                }catch (Exception e) {
                    showErrorView(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                pull_to_refresh_pro.setRefreshing(false);
                showErrorView(2);
            }

            @Override
            public void onFinish() {
//                dismissDialog();
                bottom_load_progressbar.setHide();
                pull_to_refresh_pro.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(rankUrl);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

    }

    private class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            listview.setOnItemClickListener(null);
            Intent intent = new Intent(RankCategoryActivity.this, BookDesActivity.class);
            intent.putExtra("bookId",rankDataList.get(position).getId());
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        listview.setOnItemClickListener(new ItemClickListener());
    }

    @Override
    protected void setListener() {
        rl_back_layout.setOnClickListener(this);
        ll_search_img.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        //条目点击
        listview.setOnItemClickListener(new ItemClickListener());

        // 下拉刷新
        pull_to_refresh_pro.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isPullDown = true;
                mCurrentPage = 1;
                pull_to_refresh_pro.setLoading(false);
                getDataFromNet(false);
            }
        });
        //上拉加载
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }

            @Override
            public void onScrollStateChanged(AbsListView absListView, int status) {
                if (status == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        if (!ActivityUitl.isNetworkAvailable(mContext)) {
                            ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                        }else {

                            if (isShowBottomProgressBar) {
                                bottom_load_progressbar.setVisibility(View.VISIBLE);
                            }else {
                                bottom_load_progressbar.setVisibility(View.GONE);
                            }

                            mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                            isPullDown = false;
                            getDataFromNet(false);

                        }
                    }
                }
            }
        });
    }


    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()) {
            case R.id.rll_back_layout:
                finish();
                break;
            case R.id.ll_search_img:
                startActivity(new Intent(RankCategoryActivity.this, BookSearchActivity.class));
                break;
            case R.id.common_refresh_net:
                isPullDown = true;
                circleProgressBar.setVisibility(View.VISIBLE);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                common_refresh_net.setOnClickListener(null);
                if (ActivityUitl.isNetworkAvailable(RankCategoryActivity.this)) {
                    getDataFromNet(false);
                }else {
                    closeCircle(System.currentTimeMillis());
                }
                break;

        }
    }

    /**
     * 显示无网络布局
     * type 为1，数据加载失败，为2 网络异常
     */
    private void showErrorView(int type) {
        settingShowOrHide(type);
        closeCircle(System.currentTimeMillis());
    }

    /**
     * 隐藏无网络的布局
     */
    private void closeErrorView() {
        circleProgressBar.setVisibility(View.GONE);
        common_loaddata_notice.setVisibility(View.GONE);
    }

    private void closeCircle(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestDataResultHandle();
                }
            }, 1000);
        }else {
            requestDataResultHandle();
        }
    }

    private void requestDataResultHandle() {
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        common_refresh_net.setOnClickListener(RankCategoryActivity.this);
    }

    /**
     * 设置错误布局的显示与隐藏
     * type为1  数据加载失败，type 为2  网络异常
     */
    String showContent;
    private void settingShowOrHide(int type) {
        if (type == 1) {
            showContent = getString(R.string.laikan_data_load_failed);
        }else if (type == 2) {
            showContent = getString(R.string.laikan_network_anomaly);
        }
        common_loaddata_notice.setVisibility(View.VISIBLE);
        common_prompt_content.setVisibility(View.VISIBLE);
        common_prompt_image.setVisibility(View.VISIBLE);
        common_refresh_net.setVisibility(View.VISIBLE);
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_prompt_content.setText(showContent);
    }
}
